﻿using AudioStudio;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 音效初始化组件，手动调用
/// </summary>
[UnityEngine.ExecuteInEditMode]

public class AudioInit : MonoBehaviour
{
    private static bool inited = false;
    public static string GlobalAudioObjectPrefab = "GlobalAudioObject";
    public State states;
    public AudioEvent events;
    public SoundBankParam[] banks;
    private GameObject audiomanager;

    public Text displaytext;

    public AkWwiseInitializationSettings InitializationSettings;

    // Use this for initialization
    void Awake()
    {
        if (!inited)
        {
            InitializationSettings = AkWwiseInitializationSettings.Instance;
#if UNITY_EDITOR
            if (!UnityEditor.EditorApplication.isPlaying)
                return;
#endif
            inited = Init();
            DontDestroyOnLoad(this);
        }
    }

    private void OnDestroy()
    {
        if (audiomanager != null)
            DestroyImmediate(audiomanager);
    }

    public bool InitFromPrefab()
    {
        GameObject go = Resources.Load<GameObject>(GlobalAudioObjectPrefab);
        if (go != null)
        {
            var clone = Instantiate(go);
            DontDestroyOnLoad(clone);
            return true;
        }
        return false;
    }

    private void LoadBanks()
    {
        if (banks == null)
            return;
        for (var i = 0; i < banks.Length; i++)
        {
            if (banks[i].load)
            {
                banks[i].bank.Load();
            }
        }
    }

    public bool Init()
    {
        //Wwise 初始化
        audiomanager = new GameObject("AudioManager");
        audiomanager.AddComponent<AkTerminator>();
        AkInitializer initializer = audiomanager.AddComponent<AkInitializer>();
        initializer.Initialize(InitializationSettings);

        audiomanager.AddComponent<AudioStudio.GlobalSoundObj>();

        AudioStudio.AudioManager.Instance.Init(audiomanager);
        LoadBanks();
        if (states!=null)
            states.SetValue();
        if (events!=null)
            events.Post();

#if (UNITY_ANDROID || UNITY_IOS) && HEADPHONEDETECT
        audiomanager.AddComponent<HeadPhoneDetect>();
#endif

        return true;
    }
}